#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from xml.dom import minidom


def addNode(doc,father,name,nodes,attrs):
    child=doc.createElement(name)
    father.appendChild(child)
    if attrs.has_key(name):
        val=attrs[name]
        splitval=val.split(";")
        for item in splitval:
            child.setAttribute(item,"00")
    if nodes.has_key(name):
        val=nodes[name]
        splitval=val.split(";")
        for item in splitval:
            addNode(doc,child,item,nodes,attrs)

if __name__ == "__main__":
    infile1=open("D:/data/pmc_meta/node_node.txt","r")
    infile2=open("D:/data/pmc_meta/node_attr.txt","r")
    nodes={}
    attrs={}
    for line in infile1:
        line=line.rstrip()
        splitline=line.split("====")
        nodes[splitline[0]]=splitline[1]
    infile1.close()

    for line in infile2:
        line=line.rstrip()
        splitline=line.split("====")
        attrs[splitline[0]]=splitline[1]
    infile2.close()

    doc = minidom.Document()
    root=doc.createElement("pmc-articleset")
    doc.appendChild(root)

    val=nodes["pmc-articleset"]
    splitval=val.split(";")
    for item in splitval:
        addNode(doc,root,item,nodes,attrs)

    # for i in xrange(1,6):
    #     child=doc.createElement("child"+str(i))
    #     child.setAttribute("attr",str(i))
    #     root.appendChild(child)

    # reparsed = minidom.parseString(doc.toprettyxml())
    # print reparsed.toprettyxml(indent="\t" , encoding="utf-8");

    print doc.toprettyxml()